package base

import (
	"path"
	"time"

	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/pkg/errors"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	log "github.com/sirupsen/logrus"
)

//ConfigLocalFilesystemLogger 配置logrus写日志到本地文件系统
func ConfigLocalFilesystemLogger() error {
	logPath, err := WorkDir()
	if err != nil {
		return err
	}
	logPath = logPath + "/log"
	logFileName := "pas"
	baseLogPaht := path.Join(logPath, logFileName)
	writer, err := rotatelogs.New(
		baseLogPaht+"%Y%m%d.log",
		rotatelogs.WithLinkName(baseLogPaht),                                              // 生成软链，指向最新日志文件
		rotatelogs.WithMaxAge(time.Hour*time.Duration(Context.Logrun.MaxAge)),             // 文件最大保存时间
		rotatelogs.WithRotationTime(time.Hour*time.Duration(Context.Logrun.RotationTime)), // 日志切割时间间隔
	)
	if err != nil {
		log.Errorf("config local file system logger error. %+v", errors.WithStack(err))
	}
	lfHook := lfshook.NewHook(
		lfshook.WriterMap{
			log.DebugLevel: writer, // 为不同级别设置不同的输出目的
			log.InfoLevel:  writer,
			log.WarnLevel:  writer,
			log.ErrorLevel: writer,
			log.FatalLevel: writer,
			log.PanicLevel: writer,
		},
		&logrus.TextFormatter{})
	log.AddHook(lfHook)
	return nil
}
